﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Forms;
using System.Threading;

namespace TELOS_Konverter
{
    /// <summary>
    /// Interaktionslogik für MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        FileHandler fh = new FileHandler();
        MessageHandler mh = new MessageHandler();
        ErrorHandler eh = new ErrorHandler();
        FileOperations fo = new FileOperations();
        StringHandler sth = new StringHandler();

        private string lastAccessedPath = "";
        
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            FolderBrowserDialog objDialog = new FolderBrowserDialog();
            objDialog.Description = "Please choose the root directory of files to be changed";
            
            // If the open file dialog has never been opened before, save the chosen directory as "My Computer" folder
            if (lastAccessedPath.Equals(""))
                lastAccessedPath = @Environment.GetFolderPath(Environment.SpecialFolder.MyComputer);
            
            // Set starting path to the last accessed one
            objDialog.SelectedPath = lastAccessedPath;

            if (objDialog.ShowDialog().ToString() == "OK")
            {
                // clear all items from the tree view
                treeView.Items.Clear();
                // put the selected path into the txt filed so the user can see what is going to happen to "where"
                txtFile.Text = objDialog.SelectedPath + "\\";
                // save the selected path so it can later be used to set the Open Folder Dialog to this one
                lastAccessedPath = objDialog.SelectedPath + "\\";

                //foreach (string s in fh.DirSearch(getSelectedPath()))
                //    treeView.Items.Add(fo.getFileFromPath(s));
            }
            else
                mh.alert("Abbruch gewählt!");
        }

        private TreeNode TraverseDirectory(string path)
        {
            TreeNode result = new TreeNode(path);
            foreach (var subdirectory in Directory.GetDirectories(path))
            {
                result.Nodes.Add(TraverseDirectory(subdirectory));
            }

            return result;
        }
                 
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            
        }

        #region GETTER METHODS FOR OBJECTS

        private object getCopyrightInfoObject() { return txtCopyright; }
        private object getMediaFilePathObject() { return txtMediaFilePath; }
        private object getMediaFileDirObject() { return txtMediaFileDir; }
        private object getMediaFileObject() { return txtMediaFile; }
        private object getSAMIWebFilePathObject() { return txtSMIFilePath; }
        private object getSAMIWebFileDirObject() { return txtSMIFileDir; }
        private object getSAMIWebFileObject() { return txtSMIFile; }
        private object getTextBlockStatus() { return this.txtblkStatus; }

        private String getCopyright() { return (getCopyrightInfoObject() as System.Windows.Controls.TextBox).Text; }

        private String getMediaFilePath()   { return (getMediaFilePathObject()  as System.Windows.Controls.TextBox).Text; }
        private String getMediaFileDir()    { return (getMediaFileDirObject()   as System.Windows.Controls.TextBox).Text; }
        private String getMediaFile()       { return (getMediaFileObject()      as System.Windows.Controls.TextBox).Text; }

        private String getSAMIWebFilePath() { return (getSAMIWebFilePathObject()    as System.Windows.Controls.TextBox).Text; }
        private String getSAMIWebFileDir()  { return (getSAMIWebFileDirObject()     as System.Windows.Controls.TextBox).Text; }
        private String getSAMIWebFile()     { return (getSAMIWebFileObject()        as System.Windows.Controls.TextBox).Text; }

        #endregion

        private void setTextBlockStatus(string status)
        {
            txtblkStatus.Text = status;
        }

        //private string s;

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            
            /*
            Thread t1 = new Thread(new ThreadStart(rewrite));
            t1.Start();
            */

            bool error = false;

            // Clear All Errors from the list
            eh.clearErrors();

            int count = 0;
            FileOperations.rootFolder = getSelectedPath();
            
            foreach (string s in fh.DirSearch(getSelectedPath(), fh.getHTMLTypeForSearchVideo()))
            {
                // Counter for progress indication
                count++;
                FileInformation fi = new FileInformation(getCopyright(), getMediaFilePath(), getMediaFileDir(), getMediaFile(), getSAMIWebFilePath(), getSAMIWebFileDir(), getSAMIWebFile());

                //if (s.Equals("t15_l.html")) mh.alert("pew!");

                if (!fh.rewriteFile(s, fi))
                {
                    error = true;
                    //mh.alert("Error at file: " + s);
                    break;
                }
                else
                {
                    //mh.alert("Success at " + s);
                }

                // Display a message to indicate how far the progress has come
                //setTextBlockStatus(mh.displayStatus(count.ToString(), MessageHandler.STATUS_PROGRESS));
            }

            if (error)
            {
                eh.writeErrorsToFile(); 
                mh.alert("Encountered problems. Please see error log.");
            }

            // this will edit the copyright information on every website
            insertCopyright("Verdana", 7, "black", 4);
            
            mh.alert("Finished, maybe?");
        }

        private void insertCopyright(string font, int fontSize, string color, int marginTop)
        {
            foreach (string s in fh.DirSearch(getSelectedPath(), fh.getHTMLTypeForSearchCopyright()))
            {
                List<string> website = fo.readFile(s);
                bool copyrightSet = false;
                for (int i = 0; i < website.Count; i++)
                {
                    website[i].Replace("’", "'");
                    if (!copyrightSet)
                    {
                        if ( (sth.isStringInString(website[i].ToLower(), "<font face=")) &&
                             (sth.isStringInString(website[i].ToLower(), "verdana")) &&
                             (sth.isStringInString(website[i].ToLower(), "copyright")))
                        {
                            website[i] = "<div style=\"text-align: center; font-family:"+font+"; font-size: "+fontSize+"pt; color: "+color+"; margin-top: "+marginTop+"px; \">" + fo.getCopyright() + "</div>";
                            copyrightSet = true;
                        }
                    }
                }

                fo.writeFile(s, website);
            }
        }

        private string getSelectedPath()
        {
            //return this.lastAccessedPath;
            return txtFile.Text;
        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
            if (cmbxProjekt.SelectedIndex == 0)
            {
                txtCopyright.Text = "© Copyright 2003 ÚVVPLVH SR";
                txtMediaFileDir.Text = "mms://u-003-stimms08.uni-tuebingen.de/ne/neskk06/ilegefos/";
                txtSMIFileDir.Text = "http://projects.ael.uni-tuebingen.de/ilegefos/t1wbau/";
                txtFile.Text = "C:\\Users\\Achim\\crap\\ilegefos\\t1wbau\\t1m1\\";
                mh.alert("Projekt \"Ilegefos\" ausgewählt.");
            }
        }

    }
}
